﻿using System;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Reflection;
using System.Windows.Forms;
using System.Collections.Generic;
using DevComponents.DotNetBar;
using ESRI.ArcGIS.esriSystem;
using PlanningGIS.Framework;
using PlanningGIS.Win.Controls;
using PlanningGIS.ArcGIS;
using PlanningGIS.Framework.Rule;
using PlanningGIS.Util.Convertor;
using PlanningGIS.Util.Management;
using PlanningGIS.ManageUtility.Modules;
using PlanningGIS.ManageUtility.DataAccess;
using PlanningGIS.Util.Log;
using PlanningGIS.Util.IO;
using PlanningGIS.ManageUtility;
using PlanningGIS.Util.Security;
using System.Text;
using System.DirectoryServices;

namespace PlanningGIS.Framework.Controls
{
    /// <summary>
    /// 系统登陆界面
    /// </summary>
    public partial class FrmLogin : Office2007Form
    {        
        /// <summary>
        /// 本地用户信息
        /// </summary>
        private readonly string strTextpath = AppConfig.StartupPath + "\\Temp\\UserInfo.txt";
        
        /// <summary>
        /// 当前的错误次数
        /// </summary>
        private int errTimes = 0;

        /// <summary>
        /// 构造函数
        /// </summary>
        public FrmLogin()
        {
            InitializeComponent();

            this.Text = FrameworkHelper.SysName;
            string strImage = AppConfig.ImagePath + "\\login.png";
            if (System.IO.File.Exists(strImage))
            {
                try
                {
                    this.BackgroundImage = Image.FromFile(strImage);
                }
                catch
                {

                }
            }
        }

        /// <summary>
        /// 加载窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoginForm_Load(object sender, EventArgs e)
        {
            try
            {
                if (File.Exists(strTextpath))
                {
                    string s = FileHelper.ReadFile(strTextpath);
                    string[] ns = s.Split(';');
                    txtUser.Text = ns[0];                    
                }
            }
            catch
            {
            }
            finally
            {
                
            }
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtUser.Text) || string.IsNullOrWhiteSpace(txtPassword.Text))
            {
                MsgHelper.ShowErrorMsgbox(this, "用户名和密码不能为空，请输入用户名和密码！");
                return;
            }
            //if (ManageHelper.Administrator.Equals(txtUser.Text)) //超级管理员
            //{
            //    if (!Encoding.UTF8.GetString(ManageHelper.AdminPassword).Equals(txtPassword.Text))
            //    {
            //        MsgHelper.ShowErrorMsgbox(this, "用户名和密码错误，请重新输入！");
            //        return;
            //    }
            //    FrameworkHelper.CurrentUser = new User();
            //    FrameworkHelper.CurrentUser.Parse(new UserInfo()
            //    {
            //        Login_Name = ManageHelper.Administrator,
            //        Name = "超级管理员"
            //    });
            //    this.DialogResult = System.Windows.Forms.DialogResult.OK;
            //    this.Close();
            //    return;
            //}
            this.Cursor = Cursors.WaitCursor;
            Log log = new Log();
            log.USER_NAME = txtUser.Text;
            log.OP_TYPE = PlanningGIS.ManageUtility.Modules.zjgisLogType.Login;
            log.NOTES = txtUser.Text + "试图登录系统！";
            log.OP_STATUS = zjgisLogStatus.Fail;
            try
            {
                
                string adServer=   System.Configuration.ConfigurationManager.AppSettings.Get("AdServer");
               DirectoryEntry  domain = new DirectoryEntry();
                try
                {
                    domain.Path = string.Format("LDAP://{0}", adServer);
                    domain.Username = txtUser.Text.Trim();
                    domain.Password = txtPassword.Text.Trim() ;
                    domain.AuthenticationType = AuthenticationTypes.Secure;

                    domain.RefreshCache();

                   
                }
                catch (Exception ex)
                {

                    MsgHelper.ShowErrorMsgbox(this, "登陆失败！");
                    return;
                }

                Dictionary<string, dynamic> w = new Dictionary<string, dynamic>();
                w.Add("login_name", txtUser.Text);
                List<UserInfo> us = ManageHelper.DBContext.GetAllEntry<UserInfo>(w);
                if (us == null || us.Count == 0)
                {
                    log.REMARK = "当前输入的帐号不存在！";
                    MsgHelper.ShowErrorMsgbox(this, "当前帐号不存在，请重新输入！");
                    return;
                }
                try
                {
                    if (chkSave.Checked)
                    {
                        if (File.Exists(strTextpath)) File.Delete(strTextpath);
                        FileHelper.WriteFile(strTextpath, txtUser.Text + ";");
                    }                   
                }
                catch
                {
                    
                }                
                UserInfo u = us[0];                
                if (!"1".Equals(u.IsActive))
                {
                    log.REMARK = "输入的帐号不可用！";
                    MsgHelper.ShowErrorMsgbox(this, "当前帐号不可用，请联系管理员！");
                    return;
                }
                if ("lock".Equals(u.Status))
                {
                    if (ManageHelper.SecuritySet.LockTime > 0)
                    {
                        if (u.LockedTime.AddMinutes(ManageHelper.SecuritySet.LockTime) > ManageHelper.DBContext.GetSysDateTime())
                        {
                            log.REMARK = "帐号已被锁定，不能登录！";
                            FrmTimer frm = new FrmTimer();
                            frm.LockedTime = u.LockedTime;
                            frm.Show(this);
                            return;
                        }
                    }                    
                }
                FrameworkHelper.CurrentUser = new User();
                FrameworkHelper.CurrentUser.Parse(u);
                //if (ManageHelper.SecuritySet.PasswordValid > 0)
                //{
                //    if (u.EffectiveTime.AddMonths(ManageHelper.SecuritySet.PasswordValid) < ManageHelper.DBContext.GetSysDateTime())
                //    {
                //        log.REMARK = "密码已过期，不能登录！";
                //        MsgHelper.ShowErrorMsgbox(this, "密码已过期，请先修改密码！");
                //        FrmUpdatePSD frm = new FrmUpdatePSD();
                //        if (frm.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
                //        this.DialogResult = System.Windows.Forms.DialogResult.OK;
                //        this.Close();
                //        return;
                //    }
                //}
                //if (!FrameworkHelper.CurrentUser.PSD.Equals(SecurityHelper.EnCryptUnidirectional(txtPassword.Text,AppConfig.SystemConfig.基本信息.密钥)))
                //{
                //    log.REMARK = "密码输入错误，不能登录！";
                //    errTimes += 1;
                //    if (ManageHelper.SecuritySet.ErrorNumber > 0)
                //    {
                //        int n = ManageHelper.SecuritySet.ErrorNumber - errTimes;
                //        if (n <= 0)
                //        {                            
                //            u.Status = "lock";
                //            u.LockedTime = ManageHelper.DBContext.GetSysDateTime();
                //            ManageHelper.DBContext.Update<UserInfo>(u, "id", u.ID);
                //            errTimes = 0;
                //            FrmTimer frm = new FrmTimer();
                //            frm.LockedTime = u.LockedTime;
                //            frm.Show(this);
                //        }
                //        else MsgHelper.ShowErrorMsgbox(this, string.Format("密码输入错误，您还有{0}次输入密码的机会！", n)); 
                //    }
                //    else
                //    {
                //        MsgHelper.ShowErrorMsgbox(this,"密码错误，请重新输入！");   
                //    }
                //    return;
                //}
                log.OP_STATUS = zjgisLogStatus.Success;
                log.USER_ID = u.ID;
                log.USER_NAME = u.Name;
                errTimes = 0;
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                log.REMARK = "登录异常：" + ex.Message;
                MsgHelper.ShowErrorMsgbox(this, "登录异常：" + ex.Message);
                return;
            }
            finally
            {
                if (!AppConfig.IsRunLocal) Log.WriteLog(log);
                this.Cursor = Cursors.Default;
            }            
        }

        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = System.Windows.Forms.DialogResult.Cancel;
            Close();
        }

        /// <summary>
        /// 添加登陆窗口右上角的最小化和关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoginForm_MouseClick(object sender, MouseEventArgs e)
        {
            if (Math.Sqrt(Math.Pow((e.X - 540), 2) + Math.Pow((e.Y - 19), 2)) < 12)
            {
                this.Close();
            }
            if (Math.Sqrt(Math.Pow((e.X - 509), 2) + Math.Pow((e.Y - 24), 2)) < 8)
            {
                this.WindowState = FormWindowState.Minimized;
            }
        }

    }
}